package boot.controller;

import boot.controller.utils.R;
import boot.domain.Goods;
import boot.service.IGoodsService;
import com.baomidou.mybatisplus.core.metadata.IPage;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

@RestController
@RequestMapping("/goods")
public class GoodsController {
    @Autowired
    private IGoodsService goodsService;

    @GetMapping
    public R getAll() {
        return new R(true, goodsService.list());
    }

    @PostMapping
    public R save(@RequestBody Goods goods) {
        boolean flag = goodsService.save(goods);
        return new R(flag, flag ? "添加成功^_^" : "添加失败-_-");
    }

    @PutMapping
    public R update(@RequestBody Goods goods) {
        return new R(goodsService.update(goods, null));
    }

    @DeleteMapping("{id}")
    public R delete(@PathVariable Integer id) {
        return new R(goodsService.removeById(id));
    }

    @GetMapping("{id}")
    public R getById(@PathVariable Integer id) {
        return new R(true, goodsService.getById(id));
    }

    @GetMapping("{currentPage}/{pageSize}")
    public R getPage(@PathVariable int currentPage, @PathVariable int pageSize, Goods goods) {
        IPage<Goods> page = goodsService.getPage(currentPage, pageSize, goods);
        //如果当前页码值大于总页码值,那么重新执行查询操作,使用最大页码数为总页码数
        if (currentPage > page.getPages())
            page = goodsService.getPage((int) page.getPages(), pageSize, goods);
        return new R(true, page);
    }
}
